import 'dart:convert';
import 'dart:io';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_lib/utils/LogUtils.dart';
import 'package:flutter_my_web/widget/AppBarTitleWidget.dart';
import 'package:flutter_my_web/widget/BlueMaterialButton.dart';
import 'package:flutter_my_web/widget/TextWidget.dart';
import 'package:get/get.dart';
import 'package:process_run/shell.dart';

class BiliBiliPage extends StatefulWidget {
  const BiliBiliPage({Key? key}) : super(key: key);

  @override
  State<BiliBiliPage> createState() => _BiliBiliPageState();
}

class _BiliBiliPageState extends State<BiliBiliPage> {
  var directoryPathStr = "";
  var shell = Shell();
  String removeAlltr(String str){
    var s="";
    for(var i = 0; i<str.length;i++){
      if(str[i]!=' '){
        s+=str[i];
      }
    }
    return s;
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: AppBarTitleWidget("BiliBili视频转换工具"),
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          SimpleText("选择哔哩哔哩文件夹，里面有导出来的视频合集（bilibili/合集/单独文件夹/（包含entry.json））"),
          Wrap(
            children: [
              BlueMaterialButton("选择文件夹", () async {
                var directoryPath =
                    await FilePicker.platform.getDirectoryPath();
                // printDebugStr("directoryPath:${directoryPath}");
                if (directoryPath == null) {
                  printDebugStr("没有选择文件夹");
                  return;
                }
                directoryPathStr = directoryPath;
                var directory = Directory(directoryPath);
                var list = await directory.list().toList();
                // printDebugStr("获取到文件个数：${list.length}");
                bool iss = false;
                list.forEach((element) async {
                  // printDebugStr("文件：${element.path}");
                  if (element.statSync().type ==
                      FileSystemEntityType.directory) {
                    var groupdirectory = Directory(element.path);
                    var list = await groupdirectory.list().toList();
                    list.forEach((element) async {
                      if (element.statSync().type ==
                          FileSystemEntityType.directory) {
                        var groupdirectory = Directory(element.path);
                        var list = await groupdirectory.list().toList();
                        var title = "";
                        var videoPath = "";
                        var audioPath = "";
                        if (iss == false) {
                          // iss = true;
                          for (var i = 0; i < list.length; i++) {
                            var element = list[i];
                            //进入到文件层了  entry.json
                            // printDebugStr("     文件：${element.path}");
                            if (element.path.contains("entry.json")) {
                              var file = File(element.path);
                              var str = await file.readAsString();
                              var map = json.decode(str); // 解码
                              try{
                                title = map['page_data']['download_subtitle'];
                              }catch(e){
                              }
                              if( title.isEmpty){
                                title = map['title'];
                              }
                              if(title == null|| title.isEmpty){
                                LogUtils.e("${element.path} 错误");
                              }
                              title=removeAlltr(title);
                              var nameFile = File("${element.parent.path}/$title");
                              if(!nameFile.existsSync()){
                                nameFile.create();
                              }
                              // printDebugStr(str);
                              // printDebugStr(
                              //     map['page_data']['download_subtitle']);
                            }else if(element.statSync().type ==
                                FileSystemEntityType.directory){
                              var groupdirectory = Directory(element.path);
                              var list = await groupdirectory.list().toList();
                              for (var i = 0; i < list.length; i++){
                                var element = list[i];
                                if(element.path.contains("video")){
                                  videoPath = element.path.replaceAll("/Volumes/Macintosh HD", "");
                                }
                                if(element.path.contains("audio")){
                                  audioPath = element.path.replaceAll("/Volumes/Macintosh HD", "");
                                }
                              }
                            }
                          }
                          printDebugStr("$title  $videoPath   $audioPath");
                          var shell = Shell();
                          //ffmpeg -i audio.m4s -i video.m4s -codec copy out.mp4
                          var shellStr = "ffmpeg -i $videoPath -i $audioPath -codec copy /Users/xian/Desktop/biliOut/${title}.mp4";
                          printDebugStr("shell指令:$shellStr");
                          await shell.run(shellStr);
                        }
                      }
                    });
                  }
                });
              }),
            ],
          )
        ],
      ),
    );
  }

  printDebugStr(Str) {
    print(Str);
  }
}
